package com.bootdo.wx.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bootdo.common.utils.*;
import com.bootdo.wx.domain.MemberLevelChangeDO;
import com.bootdo.wx.service.MemberLevelChangeService;
import com.bootdo.wx.service.MemberScoreService;
import com.bootdo.wx.service.OrderComService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.wx.domain.MemberUserDO;
import com.bootdo.wx.service.MemberUserService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户,会员
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-05-22 15:32:07
 */
 
@Controller
@RequestMapping("/wx/memberUser")
public class MemberUserController {
	@Autowired
	private MemberUserService memberUserService;
	@Autowired
	private OrderComService orderComService;
	@Autowired
	private MemberScoreService memberScoreService;
	
	@GetMapping()
	@RequiresPermissions("wx:memberUser:memberUser")
	String MemberUser(){
	    return "wx/memberUser/memberUser";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils list(@RequestParam Map<String, Object> params){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		//查询列表数据
        Query query = new Query(params);
		List<MemberUserDO> memberUserList = memberUserService.list(query);
		int total = memberUserService.count(query);
		params.clear();
		for (MemberUserDO memberUserDO : memberUserList) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", memberUserDO.getId());
			Map<String,Object> moneyMap = orderComService.getMemberCom(map);
			memberUserDO.setMoney(new BigDecimal(moneyMap.get("allPrice").toString()));
			BigDecimal shoppingNum = memberUserService.getShoppingNum(map);
			Map<String,Object> userMap = StringUtils.entityToMap(memberUserDO);
			userMap.put("shoppingNum", shoppingNum);
			BigDecimal scoreNumber = memberScoreService.getSumByUser(map);
			userMap.put("scoreNum", scoreNumber);   //积分
			list.add(userMap);
		}
		PageUtils pageUtils = new PageUtils(list, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:memberUser:add")
	String add(){
	    return "wx/memberUser/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:memberUser:edit")
	String edit(@PathVariable("id") String id,Model model){
		MemberUserDO memberUser = memberUserService.get(id);
		model.addAttribute("memberUser", memberUser);
	    return "wx/memberUser/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:memberUser:add")
	public R save( MemberUserDO memberUser){
		if(memberUserService.save(memberUser)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:memberUser:edit")
	public R update( MemberUserDO memberUser){
		memberUserService.update(memberUser);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:memberUser:remove")
	public R remove( String id){
		if(memberUserService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:memberUser:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
		memberUserService.batchRemove(ids);
		return R.ok();
	}

	/*
	* 个人业绩图表
	* */
	@RequestMapping( "/monthMoneyEcharts")
	@ResponseBody
	public R monthMoneyEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.getOrderEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		BigDecimal[] money = new BigDecimal[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("y").toString());
			money[i] = new BigDecimal(map.get("money").toString());
		}
		return R.ok().put("month",month).put("number",number).put("money", money);
	}

	/*
	* 平台业绩图表
	* */
	@RequestMapping( "/allMoneyEcharts")
	@ResponseBody
	public R allMoneyEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.allMoneyEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		BigDecimal [] money = new BigDecimal[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("number").toString());
			money[i] = new BigDecimal(map.get("money").toString());
		}
		return R.ok().put("month", month).put("number",number).put("money", money);
	}

	/*
	* 平台会员人数图表
	* */
	@RequestMapping( "/allUserEcharts")
	@ResponseBody
	public R allUserEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.allUserEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("number").toString());
		}
		return R.ok().put("month",month).put("number", number);
	}

	/*
	* 后台查询余额列表
	* */
	@GetMapping("/goMoneyList/{id}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String goMoneyList(@PathVariable("id") String id,Model model){
		model.addAttribute("userId", id);
		return "wx/memberUser/money";
	}

	@ResponseBody
	@GetMapping("/getMoneyList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getMoneyList(@RequestParam Map<String, Object> params){
		//查询余额列表
		Query query = new Query(params);
		List<Map<String,Object>> list = memberUserService.getMoneyListByUser(query);
		int total = memberUserService.getMoneyListByUserCount(query);
		PageUtils pageUtils = new PageUtils(list, total);
		return pageUtils;
	}

	/**
	 * 导出余额记录excel表格
	 */
	@RequestMapping( "/getmoneyExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void getmoneyExcel(@RequestParam() Map<String,Object> params,
							  HttpServletResponse response,HttpServletRequest request){
		try
		{
			String userId = params.get("userId").toString();
			String name = memberUserService.get(userId).getName();
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getMoneyListByUser(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+"余额变动记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.exportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	* 得到直推人信息
	* */
	@GetMapping("/getFather/{id}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String getFather(@PathVariable("id") String id,Model model){
		MemberUserDO memberUser = memberUserService.get(id);
		MemberUserDO fatherUser = memberUserService.get(memberUser.getIntroUser());
		if (fatherUser == null) {
			fatherUser = new MemberUserDO();
		}
		model.addAttribute("fatherUser", fatherUser);
		model.addAttribute("userId", id);
		return "wx/memberUser/getFather";
	}

	//跳转我的团队页面
	@GetMapping("/getTeam/{id}")
	String getGoods(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);

		model.addAttribute("userId", userId);
		return "wx/memberUser/team";
	}
	@ResponseBody
	@GetMapping("/getTeamInfo")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getTeamInfo(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getMyFansH(query);
		int total = memberUserService.getMyFansHCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	//跳转个人消费记录页面
	@GetMapping("/getShopping/{id}")
	String getShopping(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);

		model.addAttribute("userId", userId);
		return "wx/memberUser/shopping";
	}
	@ResponseBody
	@GetMapping("/getShoppingList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getShoppingList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getShoppingList(query);
		int total = memberUserService.getShoppingListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	/**
	 * 导出个人消费记录excel表格
	 */
	@RequestMapping( "/getShoppingExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void getShoppingExcel(@RequestParam() Map<String,Object> params,
							  HttpServletResponse response,HttpServletRequest request){
		try
		{
			String userId = params.get("userId").toString();
			String name = memberUserService.get(userId).getName();
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getShoppingList(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+"消费记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.shoppingExportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	//跳转平台收入记录页面
	@GetMapping("/getPTShopping")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	String getPTShopping( Model model) {
//		UserDO userDO = userService.get(userId);
		return "wx/memberUser/ptShopping";
	}
	@ResponseBody
	@GetMapping("/getPTShoppingList")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	public PageUtils getPTShoppingList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getShoppingList(query);
		int total = memberUserService.getShoppingListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	/*
	* 平台收入总额
	* */
	@RequestMapping( "/getShoppingNum")
	@ResponseBody
	public R getShoppingNum(@RequestParam Map<String,Object> params){
		BigDecimal shoppingNum = memberUserService.getShoppingNum(params);
		return R.ok().put("data",shoppingNum);
	}

	/**
	 * 导出平台收入记录excel表格
	 */
	@RequestMapping( "/getPTShoppingExcel")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	public void getPTShoppingExcel(@RequestParam() Map<String,Object> params,
								 HttpServletResponse response,HttpServletRequest request){
		try
		{
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getShoppingList(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(("平台收入记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.shoppingExportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	//跳转个人积分记录页面
	@GetMapping("/getScore/{id}")
	String getScore(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);
		model.addAttribute("userId", userId);
		return "wx/memberUser/score";
	}
	@ResponseBody
	@GetMapping("/getScoreList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getScoreList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberScoreService.getScoreList(query);
		int total = memberScoreService.getScoreListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	//修改推荐商品页面
	@GetMapping("/editLevel/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String editLevel(@PathVariable("id") String id,Model model){
		//获取商品信息
		MemberUserDO userDO = memberUserService.get(id);
		model.addAttribute("userDO", userDO);
		return "wx/memberUser/editLevel";
	}

	/**
	 * 修改推荐商品
	 *
	 * @param
	 * @return
	 */
	@ResponseBody
	@PostMapping("/updateLevel")
	public R updateLevel(MemberUserDO userDO) {
		return memberUserService.updateLevel(userDO);
	}
	
}
